﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;

using static System.Net.Mime.MediaTypeNames;
namespace BingWallpaper
{
    class Wallpaper
    {
        public static void SetBingPaper()
        {
            try
            {
                string bingUrl = "https://cn.bing.com/HPImageArchive.aspx?n=10&mkt=zh-CN";
                //string bingUrl = "https://cn.bing.com";

                var bitmap = GetBitmap(bingUrl);
                SetWallpaper(bitmap);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        private static string GetBitmap(string bingUrl)
        {
            string msg = new StreamReader(Http(bingUrl), Encoding.UTF8).ReadToEnd();
            //string pattern = "id=\"bgImgProgLoad\" data-ultra-definition-src=\".*?\"";
            string pattern = "<url>.*?</url>";
            string pattern1 = "<copyright>.*?</copyright>";
            var m1 = Regex.Matches(msg, pattern,RegexOptions.None);
            var m2 = Regex.Matches(msg, pattern1, RegexOptions.None);
            Random r = new Random();

            int i = r.Next() % m1.Count;

            var m = m1[i];
            var name = m2[i].Value.Replace("<copyright>", "").Replace("</copyright>", "");
            name = Regex.Match(name, "^.*?\\(").Value.Trim('(').Trim();
            //if (m.Success)
            //{
            //    pattern = "\"/.*\"";
            //    m = Regex.Match(m.Value, pattern);
            //}
            string url = @"https://cn.bing.com" + m.Value.Replace("<url>","").Replace("</url>","");
            Bitmap bitmap = new Bitmap(Http(url));
            return SaveBitmap(bitmap, name);
        }

        private static Stream Http(string url)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            return req.GetResponse().GetResponseStream();
        }

        private static string SaveBitmap(Bitmap bitmap,string name)
        {
            string ResourcePath = AppDomain.CurrentDomain.BaseDirectory + "Resource/";
            if (!Directory.Exists(ResourcePath))
                Directory.CreateDirectory(ResourcePath);
            string path = ResourcePath + name + ".bmp";
            bitmap.Save(path, ImageFormat.Bmp); //图片保存路径为相对路径，保存在程序的目录下
            return path;
        }
        private static void SetWallpaper(string path)
        {
            //设置墙纸
            string strSavePath = path;
            int a = SystemParametersInfo(20, 1, strSavePath, 1);
            if(a != 1)
            {
                int errCode = Marshal.GetLastWin32Error();
                string msg = GetSysErrMsg(errCode);
                Console.WriteLine(msg);
            }
        }

        /// <summary>
        /// 获取系统错误信息描述
        /// </summary>
        /// <param name="errCode">系统错误码</param>
        /// <returns></returns>
        public static string GetSysErrMsg(int errCode)
        {
            IntPtr tempptr = IntPtr.Zero;
            string msg = null;
            FormatMessage(0x1300, ref tempptr, errCode, 0, ref msg, 255, ref tempptr);
            return msg;
        }

        [DllImport("user32.dll", EntryPoint = "SystemParametersInfo", SetLastError = true)]
        public static extern int SystemParametersInfo(
         int uAction,
         int uParam,
         string lpvParam,
         int fuWinIni
         );

        [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
        public extern static int FormatMessage(int flag, ref IntPtr source, int msgid, int langid, ref string buf, int size, ref IntPtr args);
    }
}
